package com.ce.server.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ce.server.common.RespBean;
import com.ce.server.pojo.Admin;
import com.ce.server.pojo.Menu;
import com.ce.server.pojo.Operlog;
import com.ce.server.service.IAdminService;
import com.ce.server.service.IMenuService;
import com.ce.server.service.IOperlogService;
import com.ce.server.util.AdminUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 郑爽
 * @since 2021-11-14
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

  @Autowired
  private IMenuService menuService;
  @Autowired
  private IOperlogService operlogService;

  @ApiOperation(value = "通过当前登录用户id查询菜单列表")
  @GetMapping("/menuList")
  public List<Menu> getMenusByAdminId(){
    return menuService.getMenusByAdminId();
  }

  @ApiOperation(value = "查询所有菜单")
  @GetMapping("/")
  public List<Menu> getAllRecords(){
    return menuService.list();
  }

  @ApiOperation(value = "更新菜单")
  @PutMapping("/")
  public RespBean updateRecord(@RequestBody Menu menu){
    Admin currentAdmin = (Admin) AdminUtil.getCurrentAdmin();
    operlogService.save(new Operlog().setWno(currentAdmin.getWno())
            .setWname(currentAdmin.getWname())
            .setOper("更新菜单信息").setOpertime(LocalDateTime.now()));
    return menuService.updateById(menu)?RespBean.success("更新成功！"):RespBean.error("更新失败");
  }

  @ApiOperation(value = "添加菜单")
  @PostMapping("/")
  public RespBean addRecord(@RequestBody Menu menu){
    Admin currentAdmin = (Admin) AdminUtil.getCurrentAdmin();
    operlogService.save(new Operlog().setWno(currentAdmin.getWno())
            .setWname(currentAdmin.getWname())
            .setOper("添加新的菜单信息").setOpertime(LocalDateTime.now()));
    return menuService.save(menu)?RespBean.success("添加成功！"):RespBean.error("添加失败！");
  }

  @ApiOperation(value = "删除菜单")
  @DeleteMapping("/{id}")
  public RespBean delRecord(@PathVariable Integer id){
    Admin currentAdmin = (Admin) AdminUtil.getCurrentAdmin();
    operlogService.save(new Operlog().setWno(currentAdmin.getWno())
            .setWname(currentAdmin.getWname())
            .setOper("根据id了删除菜单").setOpertime(LocalDateTime.now()));
    return menuService.removeById(id)?RespBean.success("删除成功！"):RespBean.error("删除失败！");
  }

  @ApiOperation(value = "菜单名模糊查询")
  @GetMapping("/keyName")
  public RespBean queryRecordByName(String keyname){
    List<Menu> list = menuService.list(new LambdaQueryWrapper<Menu>().like(Menu::getName, keyname));
    return list!=null?RespBean.success("查询成功！",list):RespBean.error("该菜单名不存在！");
  }
}
